package com.boot.main.service.impl;

import com.boot.main.entity.CcomUser;
import com.boot.main.entity.ScomShopCart;
import com.boot.main.mapper.CcomUserMapper;
import com.boot.main.mapper.ScomShopCartMapper;
import com.boot.main.response.ResponseData;
import com.boot.main.response.ResponseDataUtil;
import com.boot.main.service.IShopCartService;
import com.boot.main.utils.IsNotEmptyUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ShopCartService implements IShopCartService {
    @Resource
    private ScomShopCartMapper shopCartMapper;

    @Resource
    private CcomUserMapper userMapper;

    public Long getUserId(){
        Subject subject = SecurityUtils.getSubject();
        PrincipalCollection principals =  subject.getPrincipals();
        String username = (String) principals.getPrimaryPrincipal();
        CcomUser user = userMapper.getUserByUserName(username);
        Long id = user.getId();
        return id;
    }

    @Override
    public ResponseData getShopCarts(){
        Long userId = getUserId();
        List<ScomShopCart> items = shopCartMapper.getShopCarts(userId);
        for(ScomShopCart item:items){

        }
        Integer count = shopCartMapper.getTotalCount();
        Map map = new HashMap();
        map.put("datas",items);
        map.put("count", count);
        return ResponseDataUtil.success("获取购物车成功", map);
    }

    @Override
    public ResponseData saveShopCart(ScomShopCart shopCart){
        shopCart.setCreate_time(new Date().getTime());
        shopCart.setUser_id(getUserId());
        Integer num = shopCartMapper.saveShopCart(shopCart);
        if(IsNotEmptyUtil.isEmpty(num)){
            return ResponseDataUtil.error("保存购物车失败", null);
        }
        return ResponseDataUtil.success("保存购物车成功", null);
    }

    @Override
    public ResponseData updateShopCart(Long id, Integer num){
        Integer snum = shopCartMapper.updateShopCart(id, num);
        if(IsNotEmptyUtil.isEmpty(snum)){
            return ResponseDataUtil.error("修改购物车失败", null);
        }else{
            return ResponseDataUtil.success("修改购物车成功", null);
        }
    }

    @Override
    public ResponseData deleteShopCart(Long id){
        Integer num = shopCartMapper.deleteShopCart(id);
        return ResponseDataUtil.success("删除购物车成功", null);
    }
}
